package exam.huawei8_26;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;

public class test2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int step = 0;
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int used[][] = new int[n][m];
        int[][] f = new int[n][m];
        int [][] pair = {
                {1,0,-1,0},
                {0,1,0,-1}
        } ;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                f[i][j] = scanner.nextInt();
            }
        }
        Deque<int[]> q = new LinkedList<>();
        int [] firstnode = {0,0};
        q.add(firstnode);

        while(!q.isEmpty()){
            int size = q.size();
            step++;
            while(size-->0){
                int node[] = q.pollFirst();
                for (int i = 0; i < 4; i++) {
                    int x = node[0]+pair[0][i];
                    int y = node[1]+pair[1][i];
                    if(x<0||x>=n||y<0||y>=m||f[x][y]<=step||used[x][y]==1){
                        continue;
                    }
                    if(x==n-1&&y==m-1){
                        System.out.println(step);
                        return;
                    }

                    used[x][y] = 1;
                    q.add(new int[] {x,y});
                }
            }
        }

        System.out.println(-1);
    }
}
